package com.szgd.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class DocUtil {

	private Configuration configuration = null;
	private final String OUTPUT_DIR = "temp";
	private final String SLASH_MARK_PATH = "/";
	private String rootPath = "";
	private static Logger logger = Logger.getLogger(DocUtil.class);

	public DocUtil(String webRootPath) {
		configuration = new Configuration();
		configuration.setDefaultEncoding("utf-8");
		rootPath = webRootPath + SLASH_MARK_PATH + OUTPUT_DIR + SLASH_MARK_PATH;
	}

	/**
	 * 预览Pdf文档
	 * 
	 * @param response
	 * @param pdfFilePath pdf文件路径
	 */
	public void previewPdf(HttpServletResponse response,String pdfFilePath) {
		ServletOutputStream outs = null;
		try {
			File pdfFile = new File(pdfFilePath);
			byte[] bytes = getBytesFromFile(pdfFile);
			response.setContentType("application/pdf");
			response.setContentLength(bytes.length);
			outs = response.getOutputStream();
			outs.write(bytes, 0, bytes.length);
			outs.close();
			outs.flush();
		} catch (Exception e) {
			if (outs != null) {
				outs = null;
			}
			logger.error(e.getMessage());
			e.printStackTrace();
		} finally {
			if (outs != null) {
				outs = null;
			}
		}
	}
	
	/**
	 * 预览Word文档
	 * 
	 * @param response
	 * @param webRootPath
	 * @param templateName
	 * @param map
	 */
	public void previewWord(HttpServletResponse response,String webRootPath,
			String templateName, Map<String, Object> map) {
		
		ServletOutputStream outs = null;
		try {
			String tempDocName = String.valueOf(System.currentTimeMillis());
			String pdfFilePath = rootPath + tempDocName + ".pdf";
			//将xml模板转换成word文档
			String docFilePath = convertXml2Doc(templateName, map);
			//将Word文档转换成PDF
			DocConventer.word2PDF(docFilePath, pdfFilePath);

			File pdfFile = new File(pdfFilePath);
			byte[] bytes = getBytesFromFile(pdfFile);
			response.setContentType("application/pdf");
			response.setContentLength(bytes.length);
			outs = response.getOutputStream();
			outs.write(bytes, 0, bytes.length);
			outs.close();
			outs.flush();
			if (pdfFile.exists()) {
				pdfFile.delete();
				logger.info("已删除临时PDF文件" + pdfFile.getAbsolutePath());
			}
		} catch (Exception e) {
			if (outs != null) {
				outs = null;
			}
			e.printStackTrace();
			logger.error(e.getMessage());
		} finally {
			if (outs != null) {
				outs = null;
			}
		}
	}

	/**
	 * 打印word文档
	 * @param templateName xml模板
	 * @param map xml模板需要装载的数据
	 */
	public void printWordFile(String templateName,Map<String, Object> map) {
		//将xml模板文档转换成word文件
		String docFilePath = convertXml2Doc(templateName, map);
		// 调用打印方法
		DocConventer.printWordFile(docFilePath);
	}

	private static byte[] getBytesFromFile(File f) {
		if (f == null) {
			return null;
		}
		FileInputStream stream = null;
		ByteArrayOutputStream out = null;
		try {
			stream = new FileInputStream(f);
			out = new ByteArrayOutputStream(1000);
			byte[] b = new byte[1000];
			int n;
			while ((n = stream.read(b)) != -1)
				out.write(b, 0, n);
			stream.close();
			out.close();
			return out.toByteArray();
		} catch (IOException e) {
			if (stream != null) {
				stream = null;
			}
			if (out != null) {
				out = null;
			}
			e.printStackTrace();
			logger.error(e.getMessage());
			return null;
		} finally {
			if (stream != null) {
				stream = null;
			}
			if (out != null) {
				out = null;
			}
		}
	}
	
	/**
	 * 根据word文件的xml文档，生成word文档
	 * 
	 * @param templateName 模板名称
	 * @param map 参数
	 * @return
	 */
	public String convertXml2Doc(String templateName ,Map<String, Object> map) {
		String filePath = "";
		Writer write = null;
		ServletOutputStream outs = null;
		try {
			// 要填入模本的数据文件
			// 设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet，classpath，数据库装载，
			configuration.setClassForTemplateLoading(this.getClass(),
					"/com/szgd/templates");
			Template t = null;
			t = configuration.getTemplate(templateName + ".xml", "utf-8");
			t.setEncoding("utf-8");
			// 输出文档路径及名称
			String tempDocName = String.valueOf(System.currentTimeMillis());
			filePath = rootPath + tempDocName + ".doc";
			File outFile = new File(filePath);
			write = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(outFile), "utf-8"));
			t.process(map, write);
			write.close();
		} catch (Exception e) {
			if (write != null) {
				write = null;
			}
			e.printStackTrace();
			logger.error(e.getMessage());
		} finally {
			if (write != null) {
				write = null;
			}
			if (outs != null) {
				outs = null;
			}
		}
		return filePath;
	}
}
